<template>
  <div>
    <el-form style="width: 60%" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item  label="书名" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item style="width: 40%"  label="作者" prop="author">
        <el-input v-model="ruleForm.author"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
export default {
  name: "PageTwo",
  data() {
    return {
      ruleForm: {
        name: '',
        author: '',
      },
      rules: {
        name: [
          { required: true, message: '书名请输入', trigger: 'blur' },
        ],
        author: [
          { required: true, message: '作者请填写', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      const that = this;

      this.$refs[formName].validate((valid) => {
        if (valid) { // 对整个表单 校验通过。
          //添加图书：
          axios.post('http://localhost:8181/book/save', that.ruleForm).then(
              function (resp){
                console.log(resp)
                if(resp.data == "sucess"){
                  //添加成功弹出提示：
                  that.$message({
                    showClose: true, // 可关闭的消息
                    message: '《'+that.ruleForm.name+'》'+ '添加成功',
                    type: 'success'
                  });
                  //添加成功后跳转到下个界面。当前路由进行push，表示跳到哪里。
                  that.$router.push('/book')

                }else {
                  that.$message.error('出错了！');
                }

              }
          )
        } else {
          // this.$message.error('出错了！');
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>

</style>